<?php
class Popularize extends Data_Item
{
    public static function typeName ($typeKey)
    {
        switch ($typeKey)
        {
            case 'TCKFIRST':
                return '首次发布路线';
                break;

            case 'ACTFIRST':
                return '首次发布活动';
                break;

            case 'INVITE':
                return '邀请码邀请';
                break;
        }
    }

    public static function optionsStatusList ()
    {
        return array(
            'REQUEST' => '申请', 
            'SUCC'    => '已完成',
            'REJECT'  => '拒绝',
        );
    }

    public static function statusName ($status)
    {
        switch ($status)
        {
            case 'REQUEST':
                return '申请';
                break;

            case 'SUCC':
                return '已完成';
                break;

            case 'REJECT':
                return '拒绝';
                break;

            case 'REMOVED':
                return '已删除';
                break;
        }
    }

    public function __construct ($id = NULL)
    {
        $this->_commPriamryKey = 'id';
        $this->_commTableName  = 'mod_popularize_result';

        parent::__construct ();
        $this->_nid = $id;
        $this->_id  = $id;
    }

    public function userHasRequestFirstSubmittedPrize ($uid)
    {
        $query = DB::select()
            ->from('mod_popularize_result')
            ->where('uid', '=', $uid)
            ->where_open()
            ->where('taskType', '=', 'TCKFIRST')
            ->or_where('taskType', '=', 'ACTFIRST')
            ->where_close()
            ->execute();

        return $query->count() > 0;
    }

    public function userHasRequestInvitePrize ($uid)
    {
        $query = DB::select()
            ->from('mod_popularize_result')
            ->where('taskType', '=', 'INVITE')
            ->where('taskId', '=', $uid)
            ->execute();

        return $query->count() > 0;
    }

    public function userHasGotFirstSubmittedPrize ($uid)
    {
        $query = DB::select()
            ->from('mod_popularize_result')
            ->where('uid', '=', $uid)
            ->where_open()
            ->where('taskType', '=', 'TCKFIRST')
            ->or_where('taskType', '=', 'ACTFIRST')
            ->where_close()
            ->where('status', '=', 'SUCC')
            ->execute();

        return $query->count() > 0;
    }



    public function getInviteCode ($uid)
    {
        $query = DB::select(array('inviteCode', 'code'))
            ->from('mod_popularize_invite_code')
            ->where('uid', '=', $uid)
            ->execute();

        if ($query->count() == 0)
        {
            $code = $this->buildInviteCode($uid);
            DB::insert('mod_popularize_invite_code')
                ->columns (array('uid', 'inviteCode'))
                ->values (array($uid, $code))
                ->execute();
            return $code;
        }
        else
        {
            $current = $query->current();
            return $current['code'];
        }

    }

    public function getUidFromInviteCode ($inviteCode)
    {
        $query = DB::select()
            ->from('mod_popularize_invite_code')
            ->where('inviteCode', '=', $inviteCode)
            ->limit(1)
            ->execute();

        $current = $query->current();
        return Arr::get($current, 'uid');
    }

    public function getInviteMoney ()
    {
        $query = DB::select()
            ->from('mod_popularize_subject')
            ->where('type', '=', 'INVITE')
            ->limit(1)
            ->execute();

        if ($query->count() > 0)
        {
            $current = $query->current();
            return Arr::get($current, 'money', 0);
        }
        else
        {
            return NULL;
        }
    }
    
    public function hasRequest ($taskType, $taskId)
    {
        return $this->hasRecord(array(array('taskType', '=', $taskType), array('taskId', '=', $taskId)));
    }

    // 注意：
    // 1, uid 是被邀请可以获得，inviteUid 是邀请码的发出者
    public function addInvite ($uid, $inviteCode)
    {
        $inviteUid = $this->getUidFromInviteCode($inviteCode);
        if (empty($inviteUid))
            throw new Exception("邀请码无效");

        if ($uid == $inviteUid)
            throw new Exception("不能使用自己的邀请码");

        if ($this->hasRequest('INVITE', $uid))
            throw new Exception("邀请码已被使用");
            
        $this->addRequest('INVITE', $uid, $inviteUid);
    }

    public function addRequest ($taskType, $taskId, $uid)
    {
        $subject = $this->getSubjectByType ($taskType);
        if (empty($subject))
            throw new Exception ("不存在的任务请求");

        $row = array(
            'taskType' => $taskType,
            'taskId'   => $taskId,
            'uid'      => $uid,
            'created'  => DB::expr('unix_timestamp(now())'),
            'changed'  => DB::expr('unix_timestamp(now())'),
            'status'   => 'REQUEST',
            'money'    => $subject['money'],
        );

        $id = $this->insert($row);
    }

    public function getSubjectByType ($taskType)
    {
        $query = DB::select()
            ->from('mod_popularize_subject')
            ->where('type', '=', $taskType)
            ->execute();

        if ($query->count() > 0)
            return $query->current();
        else
            return NULL;
    }

    public function detail ($id = NULL)
    {
        $id = $id > 0 ? $id : $this->_id;

        $query = DB::select()
            ->from('mod_popularize_result')
            ->where('status', '!=', 'REMOVED')
            ->where('id', '=', $id)
            ->execute();

        $ret = $query->current();
        $guider    = new Guider($ret['uid']);
        $guiderInfo= $guider->getUserInfo();
        $guiderName= Arr::get($guiderInfo, 'realName', '');

        $detail    = $ret;
        $detail['guider']   = $guiderInfo;
        $detail['taskType'] = self::typeName($ret['taskType']);
        $detail['taskName'] = $this->taskName($ret['taskType'], $ret['taskId']);
        $detail['statusName'] = self::statusName ($ret['status']);
        $detail['money']      = number_format($ret['money']/ 100, 2);

        return $detail;
    }



    public function getResult ($offset, $limit)
    {
        $query = DB::select()
            ->from('mod_popularize_result')
            ->where('status', '!=', 'REMOVED')
            ->offset($offset)
            ->limit($limit)
            ->execute();

        $records = array();
        foreach ($query as $ret)
        {
            $guider    = new Guider($ret['uid']);
            $guiderInfo= $guider->getUserInfo();
            $guiderName= Arr::get($guiderInfo, 'realName', '');

            $records[] = array(
                'id'       => $ret['id'],
                'userName' => $guiderName,
                'taskType' => self::typeName($ret['taskType']),
                'taskName' => $this->taskName($ret['taskType'], $ret['taskId']),
                'statusName' => self::statusName ($ret['status']),
                'money'      => number_format($ret['money']/ 100, 2),
                'created'  => $ret['created'],
                'changed'  => $ret['changed'],
            );
        }

        return $records;
    }

    public function search ($wheres, $offset, $limit)
    {
        $count = DB::select(array('count("id")', 'counts'))
            ->from(array('mod_popularize_result', 'a'))
            ->where('a.status', '!=', 'REMOVED');
            
        $query = DB::select()
            ->from(array('mod_popularize_result', 'a'))
            ->where('a.status', '!=', 'REMOVED')
            ->offset($offset)
            ->limit($limit)
            ->order_by('a.created', 'desc');

        foreach ($wheres as $rs)
        {
            $count->where($rs[0], $rs[1], $rs[2]);
            $query->where($rs[0], $rs[1], $rs[2]);
        }

        $counts  = $count->execute()->get('counts');
        $query   = $query->execute();

        $records = array();
        foreach ($query as $ret)
        {
            $guider    = new Guider($ret['uid']);
            $guiderInfo= $guider->getUserInfo();
            $guiderName= Arr::get($guiderInfo, 'realName', '');

            $records[] = array(
                'id'       => $ret['id'],
                'userName' => $guiderName,
                'taskType' => self::typeName($ret['taskType']),
                'taskName' => $this->taskName($ret['taskType'], $ret['taskId']),
                'statusName' => self::statusName ($ret['status']),
                'money'      => number_format($ret['money']/ 100, 2),
                'created'  => $ret['created'],
                'changed'  => $ret['changed'],
            );
        }

        return array($counts, $records);
    }

    // 设置结算状态和备注
    public function setStatus ($status, $comments)
    {
        $rows = DB::update('mod_popularize_result')
            ->set(array(
                'status' => $status,
                'reason' => $comments,
            ))
            ->where('id', '=', $this->_nid)
            ->execute();

        $info = DB::select()
            ->from('mod_popularize_result')
            ->where('id', '=', $this->_nid)
            ->execute()
            ->current();

        $guiderUid = Arr::get($info, 'uid');
        if ($status == 'SUCC')
        {
            if ($info['taskType'] == 'INVITE')
                $msg = "您已成功推荐一人成为哇吖玩伴，获得现金奖励5欧元，请查看您的Paypal或支付宝收款账户";
            else
                $msg = "您已获得首次发布服务10欧奖励，请查看您的Paypal或支付宝收款账户";

            Util_Notice::addNotice(-10, $guiderUid, $msg);
        }
        else if ($status == 'REJECT')
        {
            if ($info['taskType'] == 'INVITE')
                $msg = "您的邀请奖励被拒绝";
            else
                $msg = "由于您发布的服务不符合相关要求，未能获得首次发布服务10欧元现金奖励";

            Util_Notice::addNotice(-10, $guiderUid, $msg);
        }

        return $rows > 0;
    }

    public function taskName ($type, $taskId)
    {
        if ($type == 'TCKFIRST')
        {
            $track = new App_Track($taskId);
            $detail = $track->detail();
            return Arr::get($detail, 'name');
        }
        else if ($type == 'ACTFIRST')
        {
            $activity = new App_Activity($taskId);
            $detail = $activity->detail();
            return Arr::get($detail, 'name');
        }
        else if ($type == 'INVITE')
        {
            $type = user::getUserFromUid($taskId)->getUserType();
            if ($type == 'TOURIST')
            {
                $tourist = new Tourist($taskId);
                $info    = $tourist->getUserInfo();
                return Arr::get($info, 'realName', '');
            }
            else
            {
                $guider  = new Guider($taskId);
                $info    = $guider->getUserInfo();
                return Arr::get($info, 'realName', '');
            }
        }
    }

    private function buildInviteCode($uid)
    {
        $str = strtoupper(md5($uid . 'waya123!'));
        return substr($str, 0, 16);
    }
}
